package com.example.lin.qq_home_project.fragment;


import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ListView;

import com.example.lin.qq_home_project.R;
import com.example.lin.qq_home_project.adapter.ConversationAdapter;
import com.example.lin.qq_home_project.pojo.Conversation;
import com.example.lin.qq_home_project.utils.HttpUtils;
import com.google.gson.Gson;


/**
 * A simple {@link Fragment} subclass.
 */
public class ConversationFragment extends Fragment {


    private View layout;
    private ListView lv_conversation;
    private ConversationAdapter adapter;

    public ConversationFragment() {
    }

    private String adddress = "http://api.qingchifan.com/api/event/city.json?access_token=6916a7ab1f71e43ac4eadf40a51b4ab1E4DA4EE79DE4C64C449D09318FE0784F&basicCheck=0&city=0755&multi=0&gender=0&time=0&age=0&constellation=0&occupation=0&start=0&size=20&apiVersion=2.8.0";

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        layout = inflater.inflate(R.layout.fragment_conversation, container, false);
        lv_conversation = layout.findViewById(R.id.lv_conversation);
        adapter = new ConversationAdapter(getActivity());
        lv_conversation.setAdapter(adapter);
        return layout;
    }

    @Override
    public void onActivityCreated(@Nullable Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
//        if (conversation == null) {
            HttpUtils.get(adddress, new HttpUtils.OnHttpCallback() {
                @Override
                public void onSuccess(String response) {
                    Message message = h.obtainMessage(WHAT_OK, response);
                    h.sendMessage(message);
                }

                @Override
                public void onFailure(String error) {

                }
            });
//        } else {
//            adapter.setConversation(conversation);
//        }
    }

    private Conversation conversation = null;
    public static final int WHAT_OK = 123456;

    private Handler h = new Handler(new Handler.Callback() {
        @Override
        public boolean handleMessage(Message msg) {
            switch (msg.what) {
                case WHAT_OK:
                    conversation = new Gson().fromJson(msg.obj.toString(), Conversation.class);
                    adapter.setConversation(conversation);
                    break;
            }

            return false;
        }
    });
}
